package com.hzz.framework.config;

import com.hzz.framework.util.EhcacheUtil;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.core.config.DefaultConfiguration;
import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration;
import org.ehcache.jsr107.EhcacheCachingProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.cache.CacheManager;
import javax.cache.Caching;
import java.io.File;
import java.time.Duration;

@EnableCaching
@Configuration
public class EhCacheConfig {
    @Autowired
    EhCacheProperties cacheProperties;

    @Bean
    public CacheManager initCacheManager() {
        EhcacheCachingProvider cachingProvider = (EhcacheCachingProvider) Caching.getCachingProvider(EhcacheCachingProvider.class.getName());

        DefaultConfiguration configuration = new DefaultConfiguration(cachingProvider.getDefaultClassLoader(), new DefaultPersistenceConfiguration(new File(cacheProperties.folder)));

        CacheConfigurationBuilder defaultCache = CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(cacheProperties.defaultCache.heapSize, MemoryUnit.MB).disk(cacheProperties.defaultCache.diskSize, MemoryUnit.MB, cacheProperties.defaultCache.diskPersistent).build());
        defaultCache.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(cacheProperties.defaultCache.expiryMinutes)));
        configuration.addCacheConfiguration(EhcacheUtil.defaultCache, defaultCache.build());

        CacheConfigurationBuilder queueCache = CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(cacheProperties.queueCache.heapSize, MemoryUnit.MB).disk(cacheProperties.queueCache.diskSize, MemoryUnit.MB, cacheProperties.queueCache.diskPersistent).build());
        queueCache.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(cacheProperties.queueCache.expiryMinutes)));
        configuration.addCacheConfiguration(EhcacheUtil.queueCache, queueCache.build());

        return cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), configuration);
    }

}